//
//  SlidCommonView.m
//  demoT
//
//  Created by 魏延龙 on 2020/7/29.
//  Copyright © 2020 魏延龙. All rights reserved.
//

#import "SlidCommonView.h"
#import "SlideNavigationView.h"
#import "SlidTwoLabelView.h"
#import "SlidImageView.h"
//#import <MJRefresh/MJRefreshAutoNormalFooter.h>
//#import <MJRefresh/MJRefreshHeader.h>
//#import <MJRefresh/MJRefreshAutoGifFooter.h>

// - 42 + 16 segmentTitle = 42   圆角view = 16

#define TopImageHeight ceil([UIScreen mainScreen].bounds.size.height * 0.3 + 16)

#define NaviHeight ([[UIApplication sharedApplication] statusBarFrame].size.height + 44)


@interface SlidCommonView () <UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong) UICollectionView *collectionView;

@property(nonatomic, strong) UITableView *tableView;

// 当使用单独的view时 做滑动效果
@property(nonatomic, strong) UIScrollView *scrollView;
// 下面 和collectionview tableview 同一级别的view
@property(nonatomic, strong) UIView *contentView;
// 上面内容view （包括图片、圆角view、文字label，cornerView）
@property(nonatomic, strong) UIView *topContentView;
// 带有顶部圆角的view
@property(nonatomic, strong) UIView *cornerView;
// 上方图片
@property(nonatomic, strong) UIImageView *topImageView;
// 承载collectionView顶部顶部内容的view
@property(nonatomic, strong) UIView *subDesView;
// 带有文本的view
@property(nonatomic, strong) SlidTwoLabelView *labelBox;
// 带有图片和文本的view
@property(nonatomic, strong) SlidImageView *imageViewBox;
// 导航下的占位view 当显示导航栏的时候做吸顶视图
@property(nonatomic, strong) UIView *placeHolderView;
// 自定义导航view
@property(nonatomic, strong) SlideNavigationView *navigationView;

@property(nonatomic, assign) SlidViewType slidViewType;

@end

@implementation SlidCommonView

-(instancetype)initWithSlidViewType:(SlidViewType)type {
    if (self = [super init]) {
        self.slidViewType = type;
        [self setupViews];
    }
    return self;

}

#pragma mark --UI
- (void)layoutSubviews {
    self.navigationView.frame = CGRectMake(0, 0, self.frame.size.width, NaviHeight);
    self.placeHolderView.frame = CGRectMake(0, CGRectGetMaxY(self.navigationView.frame), self.frame.size.width, self.raiseContentOffset);

    self.topImageView.frame = CGRectMake(0, 0, self.frame.size.width, TopImageHeight);
    self.cornerView.frame = CGRectMake(0, self.topImageView.frame.size.height - 16, self.topImageView.frame.size.width, 16);

    UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, self.cornerView.frame.size.width, 32)
                                                  byRoundingCorners: (UIRectCornerTopLeft | UIRectCornerTopRight)
                                                        cornerRadii: CGSizeMake(16, 16)];
    CAShapeLayer* shape = [[CAShapeLayer alloc] init];
    shape.frame = CGRectMake(0, 0, self.cornerView.frame.size.width, 32);
    [shape setPath:rounded.CGPath];
    self.cornerView.layer.mask = shape;

    if (self.slidViewType == SlidViewTypeView) {
        self.topContentView.frame = CGRectMake(0, 0, self.frame.size.width, TopImageHeight + self.raiseContentOffset);
    } else {
        self.topContentView.frame = CGRectMake(0, -(TopImageHeight + self.raiseContentOffset), self.frame.size.width, TopImageHeight + self.raiseContentOffset);
    }

    if (_subDesView) {
        if (self.subDesView.superview == self.placeHolderView) {
            self.subDesView.frame = CGRectMake(0, 0, self.frame.size.width, self.raiseContentOffset);
        } else {
            self.subDesView.frame = CGRectMake(0, TopImageHeight, self.frame.size.width, self.raiseContentOffset);
        }
    }

    if (_labelBox) {
        self.labelBox.frame = CGRectMake(0, self.topImageView.frame.size.height - 20 - 60 - self.cornerView.frame.size.height, self.frame.size.width, 60);
    }
    if (_imageViewBox) {
        self.imageViewBox.frame =CGRectMake(0, self.topContentView.frame.size.height - 180 - 20 - self.cornerView.frame.size.height, self.frame.size.width, 180);
    }
    if (_collectionView) {
        self.collectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    }
    if (_tableView) {
        self.tableView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    }
    if (_scrollView) {
        self.scrollView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    }

    self.contentView.frame = CGRectMake(0, self.topContentView.frame.size.height, self.frame.size.width, self.frame.size.height - self.topContentView.frame.size.height);
}

- (void)setupViews {
    self.topContentView = [[UIView alloc] init];
    {
        self.topContentView.autoresizesSubviews = YES;
    }

    self.topImageView = [[UIImageView alloc] init];
    {
        self.topImageView.image = [UIImage imageNamed:self.topImageName];
        self.topImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.topImageView.clipsToBounds = YES;
        self.topImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [self.topContentView addSubview:self.topImageView];
    }

    [self.topContentView addSubview:self.cornerView];

    if (self.slidViewType == SlidViewTypeCollectionView) {
        [self addSubview:self.collectionView];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        [self addSubview:self.tableView];
    } else {
        [self addSubview:self.scrollView];
    }

    self.navigationView = [[SlideNavigationView alloc] init];
    {
        [self addSubview:self.navigationView];
        self.navigationView.title = self.title;
        self.navigationView.alpha = 0;
    }

    self.placeHolderView = [[UIView alloc] init];
    {
        self.placeHolderView.hidden = YES;
        self.placeHolderView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.placeHolderView];
    }

}

-(SlidTwoLabelView *)labelBox {
    // 保证不使用时不加载
    if (!_labelBox) {
        _labelBox = [[SlidTwoLabelView alloc] init];
        _labelBox.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.topContentView addSubview:_labelBox];
        [self setNeedsLayout];
    }
    return _labelBox;
}

-(SlidImageView *)imageViewBox {
    if (!_imageViewBox) {
        _imageViewBox = [[SlidImageView alloc] init];
        _imageViewBox.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.topContentView addSubview:_imageViewBox];
        [self setNeedsLayout];
    }
    return _imageViewBox;
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        {
            [_collectionView addSubview:self.topContentView];
            _collectionView.showsVerticalScrollIndicator = YES;
            _collectionView.scrollEnabled = YES;
            _collectionView.delegate = self;
            _collectionView.dataSource = self;
            _collectionView.backgroundColor = [UIColor whiteColor];
            if (@available(iOS 11.0, *)) {
                _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            }
            _collectionView.contentInset = UIEdgeInsetsMake(TopImageHeight, 0, 0, 0);
            __weak typeof(self) weakSelf = self;
//            _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//                if (weakSelf.footerRefreshingBlock) {
//                    weakSelf.footerRefreshingBlock();
//                }
//            }];
        }
    }
    return _collectionView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        {
            [_tableView addSubview:self.topContentView];
            _tableView.delegate = self;
            _tableView.dataSource = self;
            if (@available(iOS 11.0, *)) {
                _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            }
            _tableView.contentInset = UIEdgeInsetsMake(TopImageHeight, 0, 0, 0);
            // tableView 不会自动滚动到偏移量位置
            [_tableView setContentOffset:CGPointMake(0, -TopImageHeight)];
        }
    }
    return _tableView;
}

-(UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        {
            _scrollView.alwaysBounceVertical = YES;
            _scrollView.delegate = self;
            if (@available(iOS 11.0, *)) {
                _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            }
            [_scrollView addSubview:self.topContentView];
        }
    }
    return _scrollView;
}
-(UIView *)cornerView {
    if (!_cornerView) {
        _cornerView = [[UIView alloc] init];
        _cornerView.backgroundColor = [UIColor whiteColor];
        _cornerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    }
    return _cornerView;
}
#pragma mark --public
// 部分开放方法需要collectionView tableView 分开处理
- (void)setTitle:(NSString *)title {
    _title = title;
    self.navigationView.title = title;
}

-(void)setContentTitle:(NSString *)contentTitle {
    _contentTitle = contentTitle;
    self.labelBox.contentTitle = contentTitle;
}

-(void)setContentDeseNumLines:(NSInteger)contentDeseNumLines {
    _contentDeseNumLines = contentDeseNumLines;
    self.labelBox.contentDeseNumLines = contentDeseNumLines;
}

-(void)setContentDes:(NSString *)contentDes {
    _contentDes = contentDes;
    self.labelBox.contentDes = contentDes;
}
-(void)setTopImageName:(NSString *)topImageName {
    _topImageName = topImageName;
    self.topImageView.image = [UIImage imageNamed:topImageName];
}
-(void)setBadgeImageName:(NSString *)badgeImageName {
    _badgeImageName = badgeImageName;
    self.imageViewBox.badgeImageName = badgeImageName;
}
-(void)setBadgeTitle:(NSAttributedString *)badgeTitle {
    _badgeTitle = badgeTitle;
    self.imageViewBox.badgeTitle = badgeTitle;
}
-(void)setupContentView:(UIView *)view {
    self.contentView = view;
    [self.scrollView addSubview:self.contentView];
}

-(void)setupTopContentView:(UIView *)view {
    self.subDesView = view;
    [self.topContentView addSubview:self.subDesView];

    self.subDesView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
}
-(void)setRaiseContentOffset:(CGFloat)raiseContentOffset {
    _raiseContentOffset = raiseContentOffset;
    if (_tableView) {
        self.tableView.contentInset = UIEdgeInsetsMake(TopImageHeight+raiseContentOffset, 0, 0, 0);
        // tableView 不会自动滚动到偏移量位置
        [self.tableView setContentOffset:CGPointMake(0, -TopImageHeight - raiseContentOffset)];
    } else if (_collectionView) {
        self.collectionView.contentInset = UIEdgeInsetsMake(TopImageHeight+raiseContentOffset, 0, 0, 0);
    }
}

#pragma mark -- 调用tableview 或者collectionview 方法
-(void)setSeparatorStyle:(UITableViewCellSeparatorStyle)separatorStyle {
    _separatorStyle = separatorStyle;
    self.tableView.separatorStyle = separatorStyle;
}
- (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
    if (self.slidViewType == SlidViewTypeCollectionView) {
        [self.collectionView registerClass:cellClass forCellWithReuseIdentifier:identifier];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        [self.tableView registerClass:cellClass forCellReuseIdentifier:identifier];
    }
}

- (void)registerClass:(nullable Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier {
    // 单独设置collectionView header / footer
    [self.collectionView registerClass:viewClass forSupplementaryViewOfKind:elementKind withReuseIdentifier:identifier];
}

- (__kindof UICollectionReusableView *)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    //
    return [self.collectionView dequeueReusableSupplementaryViewOfKind:elementKind withReuseIdentifier:identifier forIndexPath:indexPath];
}

- (id)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    if (self.slidViewType == SlidViewTypeCollectionView) {
        return [self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        return [self.tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    }
    return nil;
}

- (void)setupSlidCollectionViewlayout:(UICollectionViewLayout *)layout {
    self.collectionView.collectionViewLayout = layout;
}

- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated {
    if (self.slidViewType == SlidViewTypeCollectionView) {
        [self.collectionView deselectItemAtIndexPath:indexPath animated:animated];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:animated];
    }
}

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
    if (self.slidViewType == SlidViewTypeCollectionView) {
        [self.collectionView scrollRectToVisible:CGRectMake(1, 1, 1, 1) animated:NO];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        [self.tableView scrollRectToVisible:CGRectMake(1, 1, 1, 1) animated:NO];
    } else {
        [self.scrollView scrollRectToVisible:CGRectMake(1, 1, 1, 1) animated:NO];
    }
}

-(void)reloadData {
    if (self.slidViewType == SlidViewTypeCollectionView) {
        [self.collectionView reloadData];
    } else if (self.slidViewType == SlidViewTypeTableView) {
        [self.tableView reloadData];
    }
}
#pragma mark --footer处理
-(void)footerHidden:(BOOL)hide {
    if (self.slidViewType == SlidViewTypeCollectionView) {
//        self.collectionView.mj_footer.hidden = hide;
    } else if (self.slidViewType == SlidViewTypeTableView) {
//        self.tableView.mj_footer.hidden = hide;
    }
}

-(void)footerEndRefreshing {
    if (self.slidViewType == SlidViewTypeCollectionView) {
//        [self.collectionView.mj_footer endRefreshing];
    } else if (self.slidViewType == SlidViewTypeTableView) {
//        [self.tableView.mj_footer endRefreshing];
    }
}
#pragma mark --UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)slideCollectionView numberOfItemsInSection:(NSInteger)section {
    return [self.collectionViewDataSource slidCollectionView:self numberOfItemsInSection:section];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)slideCollectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self.collectionViewDataSource slidCollectionView:self cellForItemAtIndexPath:indexPath];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([self.collectionViewDataSource respondsToSelector:@selector(slidCollectionView:viewForSupplementaryElementOfKind:atIndexPath:)]) {
        return [self.collectionViewDataSource slidCollectionView:self viewForSupplementaryElementOfKind:kind atIndexPath:indexPath];
    }
    return nil;
}

#pragma mark --UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:didSelectItemAtIndexPath:)]) {
        [self.slidCommonViewDelegate slidCommonView:self didSelectItemAtIndexPath:indexPath];
    }
}


#pragma mark --UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self.tableViewDataSource respondsToSelector:@selector(numberOfSectionsInSlidTableView:)]) {
        return [self.tableViewDataSource numberOfSectionsInSlidTableView:self];
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.tableViewDataSource slidTableView:self numberOfItemsInSection:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.tableViewDataSource slidTableView:self cellForItemAtIndexPath:indexPath];
}

#pragma mark --UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:didSelectItemAtIndexPath:)]) {
        [self.slidCommonViewDelegate slidCommonView:self didSelectItemAtIndexPath:indexPath];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:heightForRowAtIndexPath:)]) {
        return [self.slidCommonViewDelegate slidCommonView:self heightForRowAtIndexPath:indexPath];
    }
    return 44;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:tableView:viewForHeaderInSection:)]) {
        return [self.slidCommonViewDelegate slidCommonView:self tableView:tableView viewForHeaderInSection:section];
    }
    return nil;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:tableView:viewForFooterInSection:)]) {
        return [self.slidCommonViewDelegate slidCommonView:self tableView:tableView viewForFooterInSection:section];
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:tableView:heightForHeaderInSection:)]) {
        return [self.slidCommonViewDelegate slidCommonView:self tableView:tableView heightForHeaderInSection:section];
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:tableView:heightForFooterInSection:)]) {
        return [self.slidCommonViewDelegate slidCommonView:self tableView:tableView heightForFooterInSection:section];
    }
    return 0;
}


#pragma mark --UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    // 头部视图偏移量
    CGFloat y = scrollView.contentOffset.y;
    if (self.slidViewType == SlidViewTypeView) {
        if (y < 0) {
            CGRect rect = self.topContentView.frame;
            rect.origin.y = y;
            rect.size.height = TopImageHeight - y;
            self.topContentView.frame = rect;
        }
        // titleView 的透明度
        CGFloat alpha = 0;
        CGFloat offset = scrollView.contentOffset.y / 50;
        alpha = offset > 1 ? 1 : offset;
        self.navigationView.containerViewAlpha = alpha;
    } else {
        if (y < (-TopImageHeight-self.raiseContentOffset)) {
            CGRect rect = self.topContentView.frame;
            rect.origin.y = y;
            rect.size.height = -y;
            self.topContentView.frame = rect;
        } else {
            if (y > -(self.subDesView.frame.size.height + NaviHeight)) {
                // 显示到placeholderview上面
                if (![self.placeHolderView.subviews containsObject:self.subDesView]) {
                    self.placeHolderView.hidden = NO;
                    [self.placeHolderView addSubview:self.subDesView];
                    self.subDesView.frame = CGRectMake(0, 0, self.frame.size.width, self.raiseContentOffset);
                    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:navigationBarChangedShow:)]) {
                        [self.slidCommonViewDelegate slidCommonView:self navigationBarChangedShow:YES];
                    }
                }
            } else {
                // 复原到topContentView上面
                if (![self.topContentView.subviews containsObject:self.subDesView]) {
                    self.placeHolderView.hidden = YES;
                    [self.topContentView addSubview:self.subDesView];
                    self.subDesView.frame = CGRectMake(0, self.topContentView.frame.size.height - self.raiseContentOffset, self.frame.size.width, self.raiseContentOffset);
                    if ([self.slidCommonViewDelegate respondsToSelector:@selector(slidCommonView:navigationBarChangedShow:)]) {
                        [self.slidCommonViewDelegate slidCommonView:self navigationBarChangedShow:NO];
                    }
                }
            }
        }
        // titleView 的透明度
        CGFloat alpha = 0;
        CGFloat offset = (scrollView.contentOffset.y + TopImageHeight / 1.5) / 50;
        alpha = offset > 1 ? 1 : offset;
        self.navigationView.viewAlpha = alpha;

    }
}
@end
